#include "choicemodel.h"
#include "pgloader.h"
#include "Sington.h"

#include <QDebug>
#include <QtConcurrent>

ChoiceModel *ChoiceModel::instance()
{
    return Sington<ChoiceModel>::getInstance();
}

ChoiceModel::ChoiceModel(QObject *parent)
    : QAbstractListModel(parent)
{
}

int ChoiceModel::rowCount(const QModelIndex &parent) const
{
    if (parent.isValid())
        return 0;
    return m_datas.size();
}

QVariant ChoiceModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
        return QVariant();
    QVariant var;
    if (ChoiceRoleName::CName == role) {
        var = QVariant::fromValue(m_datas[index.row()].m_name);
    } else if (ChoiceRoleName::CBtn == role) {
        var = QVariant::fromValue(m_datas[index.row()].m_cbtn);
    }
    return var;
}

QHash<int, QByteArray> ChoiceModel::roleNames() const
{
    QHash<int, QByteArray> roles = {
        {ChoiceRoleName::CName, "cName"},
        {ChoiceRoleName::CBtn, "cBtn"}
    };
    return roles;
}

void ChoiceModel::remove(const int index)
{
    // 最后一个添加按键不能删除
    if (index < 0 || index >= m_datas.size() - 1)
        return;
    beginRemoveRows(QModelIndex(), index, index);
    m_datas.removeAt(index);
    endRemoveRows();
}

void ChoiceModel::insert(const int index, ChoiceModelData data)
{
    if (index < 0 || index > m_datas.size())
        return;
    qDebug() << "Add new ChoiceModelData";
    beginInsertRows(QModelIndex(), index, index);
    m_datas.insert(index, data);
    endInsertRows();
}

void ChoiceModel::append(ChoiceModelData data)
{
    insert(m_datas.size(), data);
}

void ChoiceModel::onPGLoaderLoadComplete()
{
    PGLoader* loader = PGLoader::instance();
    QList<DllItem> list = loader->getItems();
    while (!list.empty()) {
        DllItem item = list.takeFirst();
        append(ChoiceModelData {
                   .m_name = item.m_info->m_name,
                   .m_cbtn = item.m_info->m_chiBtn
               });
    }
    qDebug() << "Add Component to Main Window.";
}

ChoiceModel::~ChoiceModel()
{
}
